package com.shigen.demo.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shigen.demo.Enum.HttpStatusCode;
import com.shigen.demo.bean.Result;
import com.shigen.demo.config.ConfigProperty;
import com.shigen.demo.entity.UserInfo;
import com.shigen.demo.exception.BusinessException;
import com.shigen.demo.mapper.LoginLogMapper;
import com.shigen.demo.mapper.VisitorsMapper;
import com.shigen.demo.service.IChartService;
import com.shigen.demo.util.Common.Redis;
import com.shigen.demo.util.RedisUtil;
import com.shigen.demo.util.TokenUtil;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class ChartServiceImpl implements IChartService {

  @Resource
  private LoginLogMapper loginLogMapper;
  @Resource
  private VisitorsMapper visitorsMapper;
  @Resource
  private RedisUtil redisUtil;
  @Resource
  private TokenUtil tokenUtil;
  @Resource
  private ConfigProperty configProperty;


  @Override
  public Result getChartData(String token, String userid) {

    if (configProperty.isNeedAuthod()) {
      // 比对token中的ID和传递进来的id
      // 解析得到的token，获取真正的token
      try {
        String realToken = tokenUtil.getRealToken(token);

        String userInfoStr = redisUtil.get(Redis.TOKEN_PREFIX + realToken);
        UserInfo userInfo = JSON.parseObject(userInfoStr, UserInfo.class);
        Integer useridInRedis = userInfo.getUserId();
        if (!ObjectUtil.equals(useridInRedis, Integer.valueOf(userid))) {
          return new Result(HttpStatusCode.UNAUTHORIZED);
        }
      } catch (Exception e) {
        throw new BusinessException(HttpStatusCode.UNAUTHORIZED);
      }
    }

    // 登录设备类型，网络运营商类型
    List<Map<String, Object>> platform = loginLogMapper.getPlatform();
    List<Map<String, Object>> netServer = loginLogMapper.getNetServer();

    // 在线的用户数统计
    int onlineCount = redisUtil.keys(Redis.ONLINE_INFO_PREFIX + '*').size();

    // 当前账号的登录次数
    int AccountloginCount = loginLogMapper.getLoginCount(Integer.valueOf(userid));

    // 访客数量
    int visitorsCount = visitorsMapper.getVisitorsCount();

    // 最近7天登录（活跃）次数
    int activeCountInSevenDays = loginLogMapper.getActiveCountInSevenDays();

    // 最近7天，每天的访客数、登录数、登录失败次数

    List<Map<String, Object>> visitorsInServenDays = loginLogMapper.getVisitorsInServenDays();

    List<Map<String, Object>> loginCountInsevenDays = loginLogMapper.getLoginCountInsevenDays();

    List<Map<String, Object>> loginFailedCountInsevenDays = loginLogMapper.getLoginFailedCountInsevenDays();

    // 登录地区前7
    List<Map<String, Object>> positionTopSeven = loginLogMapper.getPositionTopSeven();

    // 登录次数前7
    // 先获得总的次数
    long loginTotal = loginLogMapper.selectCount(null);

    List<Map<String, Object>> livenessTopSeven = loginLogMapper.getLivenessTopSeven();
    livenessTopSeven.forEach((e) -> {
      BigDecimal score = new BigDecimal((long) e.get("amount") * 100.0 / loginTotal).setScale(1, BigDecimal.ROUND_HALF_UP);
      e.put("score", score);
    });

    JSONObject data = new JSONObject();
    data.put("online", onlineCount);
    data.put("loginCount", AccountloginCount);
    data.put("visitorsCount", visitorsCount);
    data.put("activeCountInSeven", activeCountInSevenDays);

    Map<String, List<Map<String, Object>>> countInSevenDays = new HashMap<>();
    countInSevenDays.put("visitorsInServenDays", visitorsInServenDays);
    countInSevenDays.put("loginCountInsevenDays", loginCountInsevenDays);
    countInSevenDays.put("loginFailedCountInsevenDays", loginFailedCountInsevenDays);
    data.put("countInSevenDays", countInSevenDays);

    Map<String, List<Map<String, Object>>> netTypeAndDeviceType = new HashMap<>();
    netTypeAndDeviceType.put("platform", platform);
    netTypeAndDeviceType.put("netServer", netServer);
    data.put("netTypeAndDeviceType", netTypeAndDeviceType);

    data.put("positionTopSeven", positionTopSeven);

    data.put("livenessTopSeven", livenessTopSeven);

    data.put("queryDate", DateUtil.now());

    return Result.ok(data);
  }
}
